/*
 * @Author: your name
 * @Date: 2020-05-18 10:49:15
 * @LastEditTime: 2020-05-20 10:26:42
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \truck\platform\time_time\my_timer.h
 */
#ifndef _MY_TIMER_H
#define _MY_TIMER_H
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include "global_common.h"

#ifndef FALSE
#define FALSE 0
#endif

#ifndef TRUE
#define TRUE 1
#endif


typedef  struct sched_para t_sched_para;
typedef struct _WaitPoint
{
	pthread_mutex_t lock;
	pthread_cond_t  cond;
	uint32_t time;
	int wakeup;
} WaitPoint;
typedef  struct session_para
{
    t_sched_para *sched;
    int is_start;
    WaitPoint wp;
	uint32_t snd_time_offset;/*the scheduler time when the application send its first timestamp*/
	uint32_t snd_ts_offset;	/* the first application timestamp sent by the application */
    struct session_para *next;
}t_session;



#define RTP_TIMESTAMP_IS_NEWER_THAN(ts1,ts2) \
	((uint32_t)((uint32_t)(ts1) - (uint32_t)(ts2))< (uint32_t)(1<<31))

#define RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(ts1,ts2) \
	( ((uint32_t)((uint32_t)(ts1) - (uint32_t)(ts2))< (uint32_t)(1<<31)) && (ts1)!=(ts2) )

#define RTP_SEQ_IS_STRICTLY_GREATER_THAN(seq1,seq2)\
	(((uint16_t)((uint16_t)(seq1) - (uint16_t)(seq2))< (uint16_t)(1<<15)) && (seq1!=seq2))
#define TIME_IS_NEWER_THAN(t1,t2) RTP_TIMESTAMP_IS_NEWER_THAN(t1,t2)

#define TIME_IS_STRICTLY_NEWER_THAN(t1,t2) RTP_TIMESTAMP_IS_STRICTLY_NEWER_THAN(t1,t2)


#define wait_point_lock(wp) pthread_mutex_lock(&(wp)->lock)
#define wait_point_unlock(wp) pthread_mutex_unlock(&(wp)->lock)



#define RTP_TIMER_RUNNING 1
#define RTP_TIMER_STOPPED 0
typedef void (*tinytimefunc)(void);
struct _tinyTimer
{
	int state;
	tinytimefunc timer_init;
	tinytimefunc timer_do;
	tinytimefunc timer_uninit;
	struct timeval interval;
};
typedef struct _tinyTimer TinyTimer;


typedef  struct sched_para
{
    t_session *list;
    struct _tinyTimer *timer;
	pthread_cond_t   unblock_select_cond;
	pthread_mutex_t	lock;
	pthread_t thread;
    int thread_running;
	int time_;       /*number of miliseconds elapsed since the start of the thread */
	int timer_inc;	/* the timer increment in milisec */
}t_sched_para;

#define POSIXTIMER_INTERVAL 10000

extern t_sched_para g_timer_sched;
void timer_sched_init();
int user_session_init(t_session *session);
void user_session_deinit(t_session *session);
int user_session_send_with_ts(t_session *session,uint32_t send_ts);
#endif